﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using ThermalImagery.showForms;
using ThermalImagery.Business;
using ThermalImagery.Model;
using Leeder.Logger;
using Sunny.UI;
using ThermalImagery.Comm.Excel;

namespace ThermalImagery.Forms
{
    public partial class FrmHistory : UIPage
    {
        /// <summary>
        /// 日志
        /// </summary>
        public LogOperate LogObj => Log.GetLogger(this.GetType());
        ThermalCheckBLL thermalCheckBLL = new ThermalCheckBLL();
        PictureBLL pictureBLL = new PictureBLL();
        List<ThermalCheckModel> datas = new List<ThermalCheckModel>();
        //List<EntityDgvLine> dgvLineList = new List<EntityDgvLine>();

        bool isLoad = true;      //判断窗体是否首次加载
        int pageSize = 30;       //数据表每页默认行数

        public FrmHistory()
        {
            InitializeComponent();
            dgvHistory.AutoGenerateColumns = false;
            dgvHistory.ReadOnly = true;

            dgvHistory.AddColumn("OK区域数量", "Value");
            dgvHistory.AddColumn("检测结果", "CheckResult");
            dgvHistory.AddColumn("检测时间", "CheckTime");

            dgvHistory.Columns[2].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss ";

            dgvPicture.AutoGenerateColumns = false;
            dgvPicture.ReadOnly = true;
            dgvPicture.AddColumn("区域ID", "Region",20);
            dgvPicture.AddColumn("温度", "FCurrTemperature",20);
            dgvPicture.AddColumn("图片", "PictureName",60);

        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            string checkResult = "";

            if(!cbResult.Text.Equals("全部") )
            {
                checkResult = cbResult.Text;
            }
            datas = thermalCheckBLL.GetModelListByCondition(dpStartDate.Value, dpEndDate.Value, checkResult).OrderByDescending(t => t.CheckTime).ToList();
            uiPagination1.TotalCount = datas.Count;
            uiPagination1_PageChanged(null,null,1, pageSize);
        }

        private void btnPieChart_Click(object sender, EventArgs e)
        {
            var NG_COUNT =
            (from entity in datas
             where entity.CheckResult == "NG"
             select entity).ToList().Count();
            var OK_COUNT =
            (from entity in datas
             where entity.CheckResult == "OK"
             select entity).ToList().Count();
            FrmPieChart frmPieChart = new FrmPieChart();
            FrmPieChart.Info.OK_COUNT = OK_COUNT;
            FrmPieChart.Info.NG_COUNT = NG_COUNT;
            frmPieChart.Show();
        }

        private void FrmHistory_Load(object sender, EventArgs e)
        {
            //设置开始时间为一星期前
            this.dpStartDate.Value = DateTime.Now.AddDays(-7);
            this.dpEndDate.Value = DateTime.Now;

            pageSize = (dgvHistory.Size.Height-30) / 23;
            datas = thermalCheckBLL.GetModelListByCondition(dpStartDate.Value, dpEndDate.Value, "").OrderByDescending(t => t.CheckTime).ToList();

            //设置分页控件总数
            uiPagination1.TotalCount = datas.Count;

            //设置分页控件每页数量
            uiPagination1.PageSize = pageSize;

            uiPagination1_PageChanged(null, null, 1, pageSize);

            //如果窗体已经加载过则不重新加载
            if (!isLoad)
                return;
            isLoad = false;
            uiPagination1.Style = UIStyle.Blue;
        }

        private void uiPagination1_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            //一般通过ORM的分页去取数据来填充
            //pageIndex：第几页，和界面对应，从1开始，取数据可能要用pageIndex - 1
            //count：单页数据量，也就是PageSize值
            List<ThermalCheckModel> data = new List<ThermalCheckModel>();
            for (int i = (pageIndex - 1) * count; i < (pageIndex - 1) * count + count; i++)
            {
                if (i >= datas.Count) continue;
                data.Add(datas[i]);
            }
            dgvHistory.DataSource = data;
            dgvHistory.Refresh();
        }

        private void dgvHistory_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            var entity = dgvHistory.CurrentRow.DataBoundItem as ThermalCheckModel;
            var pictures = pictureBLL.GetModelByCheckId(entity.ID);
            dgvPicture.DataSource = null;
            dgvPicture.DataSource = pictures.OrderBy(x=>x.Region).ToList();
            if (pictures.Count > 0)
            {
                try
                {
                    this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\picture\\" + pictures[0].PictureName);
                }
                catch (Exception ex)
                {
                    UIMessageBox.ShowError("该记录图片已过期或损坏！");
                }
            }
            else
                this.pictureBox1.Image = null;
        }

        private void dgvPicture_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                var model = dgvPicture.CurrentRow.DataBoundItem as PictureModel;
                this.pictureBox1.Image = Image.FromFile(Application.StartupPath + "\\picture\\" + model.PictureName);
            }
            catch(Exception ex)
            {
                UIMessageBox.ShowError("该记录图片已过期或损坏！");
            }
        }

        /// <summary>
        /// 列表增加自动编号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridView dgv = (DataGridView)sender;
            //自动编号，与数据无关
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void uiButton1_Click(object sender, EventArgs e)
        {
            if (datas.Count ==0)
            {
                UIMessageBox.ShowError("没有可以导出的数据！");
                return;
            }
            FolderBrowserDialog myDialog = new FolderBrowserDialog();
            myDialog.ShowNewFolderButton = false;
            myDialog.Description = "选择你要设置的文件夹或目录 ";
            string path = string.Empty;
            if (myDialog.ShowDialog() == DialogResult.OK)
                path = myDialog.SelectedPath;
            else
            {
                myDialog.Dispose();
                return;
            }
            ExcelConfig excelConfig = new ExcelConfig();
            List<ColumnEntity> columnEntities = new List<ColumnEntity>();
            columnEntities.Add(new ColumnEntity {Column = "Value", ExcelColumn = "检测OK值"});
            columnEntities.Add(new ColumnEntity { Column = "CheckResult", ExcelColumn = "检测结果" });
            columnEntities.Add(new ColumnEntity { Column = "CheckValue", ExcelColumn = "检测温度值" });
            columnEntities.Add(new ColumnEntity { Column = "CheckTime", ExcelColumn = "检测时间" });
            excelConfig.ColumnEntity = columnEntities;
            //string path = ".\\Excel\\";
            excelConfig.FileName = path+ "\\除雾检测记录表.xlsx";
            List<ExcelImportModel> list = new List<ExcelImportModel>();
            foreach(var item in datas)
            {
                ExcelImportModel excelImportModel = new ExcelImportModel();
                excelImportModel.Value = item.Value;
                excelImportModel.CheckResult = item.CheckResult;
                excelImportModel.CheckTime = item.CheckTime;
                var pictures = pictureBLL.GetModelByCheckId(item.ID);
                pictures.ForEach(x =>
                {
                    excelImportModel.CheckValue += x.FCurrTemperature + "；";
                });
                excelImportModel.CheckValue = excelImportModel.CheckValue.Substring(0, excelImportModel.CheckValue.Length - 1);
                list.Add(excelImportModel);
            }
            try
            {
                ExcelHelper<ExcelImportModel>.ExcelImport(list, excelConfig);
                UIMessageBox.Show("数据导出完成！");
            }
            catch(Exception ex)
            {
                LogObj.Error("数据导出失败,失败原因：" + ex.Message);
                UIMessageBox.ShowError("数据导出失败！");
            }
        }
    }
}
